package com.blue.base.security.exception;

import com.alibaba.fastjson.JSON;
import com.blue.base.common.bean.resp.JsonResult;
import com.blue.base.common.exception.BaseException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 身份认证失败处理器
 *
 * @author liulei
 * @version 1.0
 */
@Slf4j
public class AuthFailLoginHandler extends SimpleUrlAuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        String message = exception.getMessage();
        if (exception.getCause() instanceof BaseException) {
            logger.error("自定义登录异常....");
            BaseException baseException = (BaseException) exception.getCause();
            response.getWriter().write(JSON.toJSONString(JsonResult.define(baseException.getCode(), baseException.getErrorMessage())));
            return;
        }
        if (exception instanceof BadCredentialsException) {
            logger.error("系统登录异常....");
            response.getWriter().write(JSON.toJSONString(JsonResult.define(600, "用户名/密码错误")));
            return;
        }
        logger.error("系统登录未知异常....");
        response.getWriter().write(JSON.toJSONString(JsonResult.failed(message)));
    }
}
